# coding: utf-8

import os
import datetime

from flask import (
    render_template, redirect, request, current_app, url_for
)
from flask_login import login_required, current_user

from app.ccws.constant import QueueState
from app.codes import PARAMETER_REQUIRED
from app.utils import ApiResponse
from app.op.models import Audio, Demand
from . import outbound_bp
from .constant import CallState
from .models import OutBoundRecord
from .outbound_forms import SearchOutboundForm


@outbound_bp.route('/outbound_list', methods=['GET', 'POST'])
@login_required
def outbound_list():
    form = SearchOutboundForm(formdata=request.form or request.args)

    outbound_query = OutBoundRecord.query
    query_kwargs = {}
    if form.validate():
        query_kwargs, _ = form.generate_kwargs()

        outbound_query = OutBoundRecord.generate_list_query_condition(
            args=query_kwargs,
            query=outbound_query
        )

    page = request.args.get('page', 1, type=int)
    pagination = outbound_query.order_by(
        OutBoundRecord.created_at.desc()).paginate(
        page, per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],
        error_out=False)
    outbounds = pagination.items

    return render_template(
        'outbound/outbound_list.html',
        form=form,
        outbounds=outbounds,
        pagination=pagination,
        url_kwargs=query_kwargs,
    )


@outbound_bp.route('/waiting_outbound_list', methods=['GET', 'POST'])
@login_required
def waiting_outbound_list():
    outbounds = OutBoundRecord.query.filter_by(
        queue_state=QueueState.WAITING.value
    ).order_by(
        OutBoundRecord.call_weight.asc(),
        OutBoundRecord.schedule_time.asc()
    ).all()

    return render_template(
        'outbound/waiting_outbound_list.html',
        outbounds=outbounds
    )


@outbound_bp.route('/reset_outbound', methods=['GET'])
@login_required
def reset_outbound():
    outbounds = OutBoundRecord.query.filter_by(
        queue_state=QueueState.HANDLING.value
    ).all()
    for i in outbounds:
        i.queue_state = QueueState.DONE.value

    return redirect(url_for(
        'outbound_bp.waiting_outbound_list'
    ))


@outbound_bp.route('/cancel_outbound/<record_id>', methods=['GET'])
@login_required
def cancel_outbound(record_id):
    """
    add by zhouhl 2017-09-05
    取消外呼
    """
    outbound_record = OutBoundRecord.query.get(record_id)
    outbound_record.queue_state = QueueState.CANCEL.value
    outbound_record.call_state = CallState.CANCLE_CALL.value
    outbound_record.admin_id = current_user.id
    outbound_record.admin_nickname = current_user.nickname
    return redirect(request.referrer)


@outbound_bp.route('/seven_moor_audio/upload/<mobile>', methods=['POST'])
def seven_moor_audio(mobile):
    """
    add by zhouhl 2018-01-12
    七陌录音上传接口
    mobile 保证是客户的真实号码
    """
    # NOTE by zhouhl 暂时保留，为以后分布式架构做准备
    try:
        json_body = request.get_json()
        audio_file_name = json_body.get('audio_file_name', '')
        record_datetime = request.args.get('record_datetime').replace('_', ' ')
        call_id = request.args.get('call_id')
        date_info = request.args.get('date_info') \
            or datetime.date.today().strftime('%Y%m%d')

        # 保存文件这部分的代码，转移到 celery.task 里面了，直接在10M的机器上运行
        # views这边只负责写入Audio记录了
        save_file_dir = os.path.join(
            current_app.config['MEDIA_PATH'],
            date_info
        )
        save_file_path = os.path.join(save_file_dir, audio_file_name)
        tmp_audio_path = '/'.join(save_file_path.split('/')[-3:])
        tmp_record_date = datetime.date(
            *time.strptime(date_info, "%Y%m%d")[0:3])
        audio_record = Audio.create(
            mobile=mobile,
            audio=tmp_audio_path,
            record_date=tmp_record_date,
            record_datetime=record_datetime,
            seven_moor_call_id=call_id,
        )

        # 如果存在该 seven_moor_call_id 的 Demand， 则关联录音
        demand = Demand.query.filter_by(seven_moor_call_id=call_id).first()
        if demand:
            demand.audio = audio_record.audio

        return ApiResponse()
    except KeyError as e:
        missing_key = e.args[0]
        return ApiResponse(
            code=PARAMETER_REQUIRED.new_format_msg(missing_key)
        )
